package sysAuth

import initConfig.SysInitData

class SysNotice {
    String title;
    String content;
    String type = "0" //通知类型：0，public ；1，private
    String toUser ; //通知类型如果为 private ，则该字段必填:用户ID 消息 给谁
    int remainDay = 7//有效时长 ：天
    String state = "1" //是否有已读：1 否，0.是
    String delFlag = "0" //是否删除:0 否，1 是
    Long parentId ; //回复notice

    String creator ;//操作人
    String updater;//最近一次更新人

    Date dateCreated;
    Date lastUpdated;
    static constraints = {
        title(nullable: false)
        content(nullable: false,maxSize: 3000)
        type(nullable: false)
        state(nullable: false)
        toUser(nullable: true)
        remainDay(nullable: false)
        parentId(nullable: true)

        creator(nullable: false)
        updater(nullable: true)
    }

    static mapping = {
        version false
    }

    static init(dataSource){
        if(SysNotice.count() ==0){
            new SysNotice(title: "系统通知",content: "欢迎您使用XD后台管理系统",creator:SysInitData.SYS_ADMIN).save(flush: true)
        }
        Thread.start("Update Notice State..."){
            while (true){ //定时更新public消息状态
                this.sleep(1000*60*60*2)
                def cal = Calendar.getInstance();
                cal.setTime(new Date())
                def now = cal.getTimeInMillis();

                try {
                    def db = new groovy.sql.Sql(dataSource: dataSource)
                    def list = SysNotice.findAllByStateAndType("1","0");
                    list.each {
                        def createDate = it.getDateCreated().getTime() + Long.parseLong(String.valueOf(it.remainDay?  1000*86400 * it.remainDay : 0))
                        if( createDate < now){
                            def sql = "update Sys_Notice set state = '0' where id = ${it.id}"
                            db.executeUpdate(sql)
                        }
                    }
                }catch (Exception e){
                    new RuntimeException("Update Notice Error.........${e.getMessage()}")
                }
                print("Update Notice complete,waiting next.....")
            }
        }
    }

}
